from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin

from .models import BookInfo
from .serializer import BookSerializer


class BooksView(GenericAPIView, CreateModelMixin, ListModelMixin):
    """获取所有图书、保存图书"""

    queryset = BookInfo.objects.all()  # 指定当前类视图使用的查询集数据
    serializer_class = BookSerializer  # 指定当前类视图使用的序列化器

    def get(self, request):
        """获取所有图书"""
        return self.list(request)

    def post(self, request):
        """保存图书"""
        return self.create(request)


class BookView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    """获取单一图书、更新图书、删除图书"""

    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer

    def get(self, req, pk):  # 这个形参必须叫pk
        """获取单一图书"""
        return self.retrieve(req, pk)

    def put(self, req, pk):
        """更新图书"""
        return self.update(req, pk)

    def delete(self, req, pk):
        """删除图书"""
        return self.destroy(req, pk)

